#include "key.h"

u8 over_flag = 1;

void key_init(void){
	GPIO_InitTypeDef GPIO_InitStructure;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

  /* Configure PD0 and PD2 in output pushpull mode */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_8;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
}

void led_init(void){
	GPIO_InitTypeDef GPIO_InitStructure;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD, ENABLE);

  /* Configure PD0 and PD2 in output pushpull mode */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(GPIOD, &GPIO_InitStructure);
	
	GPIO_SetBits(GPIOC,GPIO_Pin_8);
	GPIO_SetBits(GPIOD,GPIO_Pin_2);
	GPIO_ResetBits(GPIOD,GPIO_Pin_2);
}

void delay_ms(u32 nTime)
{
	TimingDelay = nTime;
	while(TimingDelay != 0);	
}

void led_ctrl(u8 status){
	if(status == 0){
		GPIO_ResetBits(GPIOC,GPIO_Pin_8);
		GPIO_SetBits(GPIOD,GPIO_Pin_2);
		GPIO_ResetBits(GPIOD,GPIO_Pin_2);
	}else if(status == 1){
		GPIO_SetBits(GPIOC,GPIO_Pin_8);
		GPIO_SetBits(GPIOD,GPIO_Pin_2);
		GPIO_ResetBits(GPIOD,GPIO_Pin_2);
	}
}

u8 key_scan(void){
	static u8 key_flag = 0;
	if((key_flag == 0)&&((RB1&RB2)==0)){
		delay_ms(12);
		key_flag = 1;
		if(RB1 == 0)
			return key1;
		else if(RB2 == 0)
			return key2;
	}else if((RB1&RB2)==1)
		key_flag = 0;
	return 0;
}

void write_data(u8 addr,u8 data){
	I2CStart();
	I2CSendByte(0xa0);
	I2CWaitAck();
	
	I2CSendByte(addr);
	I2CWaitAck();
	
	I2CSendByte(data);
	I2CWaitAck();
	I2CStop();
}

u8 read_data(u8 addr){
	u8 temp;
	
	I2CStart();
	I2CSendByte(0xa0);
	I2CWaitAck();
	
	I2CSendByte(addr);
	I2CWaitAck();
	
	I2CStart();
	I2CSendByte(0xa1);
	I2CWaitAck();
	temp = I2CReceiveByte();
	I2CWaitAck();
	
	I2CStop();
	return temp;
}

void speed_over(void){
	if(Vim > 25)
		over_flag = 0;
	else if(Vim <= 25)
		over_flag = 1;
}

void deal_key(void){
	u8 key = key_scan();
	
	if(key == key1){
		if(set_fre < 20)
			set_fre ++;
			pwm_init_again();
	}else if(key == key2){
		if(set_fre > 0)
			set_fre--;
			pwm_init_again();
	}
}